//
//  SearchShopViewController.m
//  OrderSeat
//
//  Created by 王威 on 13-12-22.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "SearchShopViewController.h"
#import "ShopInfoCell.h"
#import "ShopHomeViewController.h"

@implementation SearchShopViewController

- (id)init
{
    self = [super initWithNibClass:[SearchShopViewController class]];
    if (self) {
        _dataSource = [[SearchShopDataSource alloc] initWithVC:self];
    }
    return self;
}

- (id)initWithKeyword:(NSString *)keyword
{
    self = [self init];
    if (self) {
        self.keyword = keyword;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    
    if (_keyword && ![_keyword isEqualToString:@""]) {
        [_dataSource searchWithKeyWord:_keyword isLoadMore:NO];
    }
}

#pragma 隐藏tabbar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

- (void)setupUI
{
    [self createLeftButton];
    [self createNavigation:@"搜索餐厅"];
    
    _shopTable.dataSource = _dataSource;
    _shopTable.delegate = _dataSource;
    
    if (_keyword)_searchTF.text = _keyword;
    [_searchTF leftMargin:10];
}

#pragma 返回按钮事件
- (void)leftButtonClick:(id)sender
{
    [AppDelegate changeToNormalTabBar];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma 将分页加载的数据添加到tableview后面
- (void)appendTableWith:(NSMutableArray *)data
{
    for (int i = 0; i < [data count]; i++) {
        [_dataSource.shopList addObject:[data objectAtIndex:i]];
    }
    
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:10];
    
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:[_dataSource.shopList indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    
    [self.shopTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    
    self.moreLoading = NO;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        [_searchTF resignFirstResponder];
        [self searchAction:nil];
        return NO;
    }
    
    return YES;
}

- (IBAction)searchAction:(id)sender
{
    NSString *keyword = _searchTF.text;
    if ([keyword isEqualToString:@""]) {
        [AppDelegate showMessage:@"请输入关键字进行搜索！"];
        return;
    }
    
    [_dataSource searchWithKeyWord:keyword isLoadMore:NO];
}

- (void)searchFinish
{
    [self.shopTable reloadData];
    [self.shopTable scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
    [self addEmptyText];
}

- (void)addEmptyText
{
    if (_dataSource.shopList.count == 0) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 130, self.view.width, 30)];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:20];
        label.textColor = [UIColor grayColor];
        label.text = @"没有搜索到相关的餐厅";
        label.tag = 1234;
        [self.view addSubview:label];
    }else {
        UIView *view = [self.view viewWithTag:1234];
        [view removeFromSuperview];
    }
}

@end

//=========================================================================================
#pragma ===================数据源类实现======================================================
//=========================================================================================

#define FETCH_NEW_TAG  1001
#define FETCH_MORE_TAG 1002
#define PAGE_COUNT 5

@implementation SearchShopDataSource

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
        _shopList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    return self;
}

#pragma 获取附近餐厅信息
- (void)searchWithKeyWord:(NSString *)keyword isLoadMore:(BOOL)isLoadMore
{
    [SVProgressHUD show];

    self.pageNumber = isLoadMore ? self.pageNumber : 1;

    NSString *url = [NSString stringWithFormat:API_SHOP_SEARCH,[AppSetting longitude],[AppSetting latitude],keyword,self.pageNumber,[AppSetting cityId]];
    [self get:url tag:isLoadMore ? FETCH_MORE_TAG:FETCH_NEW_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [SVProgressHUD dismiss];
    NSDictionary *json = [request.responseData JSONValue];
    
    //从新获取餐厅信息，是取第一页
    if (request.tag == FETCH_NEW_TAG) {
        self.shopList = [json objectForKey:@"dinner"];
        [_viewController searchFinish];
    }
    
    //分页获取餐厅信息，是加载更多
    if (request.tag == FETCH_MORE_TAG) {
        [self.viewController appendTableWith:[json objectForKey:@"dinner"]];
    }
}

#pragma ===================加载tableview数据 Begin================================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shopList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ShopInfoCell";
    
    ShopInfoCell *cell = (ShopInfoCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[ShopInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setBackgroundColor:[UIColor clearColor]];
    }
    
    NSDictionary *dic = [self.shopList objectAtIndex:indexPath.row];
    [cell setContent:dic];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [self.shopList objectAtIndex:indexPath.row];
    NSString *shopId = [dic objectForKey:@"id"];
    
    ShopHomeViewController *shopHomeVC = [[ShopHomeViewController alloc] initWithId:shopId];
    shopHomeVC.parentViewController = self.viewController;
    shopHomeVC.shopId = shopId;
    
    [AppDelegate changeToShopTabBar:shopHomeVC];
    [self.viewController pushViewController:shopHomeVC];
}

-(void)tableView:(UITableView *)tableView  willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == _shopList.count-2 && _shopList.count >= 5) {
        if (!self.viewController.moreLoading) {
            self.pageNumber++;
            
            [self searchWithKeyWord:_viewController.keyword isLoadMore:YES];
            
            self.viewController.moreLoading = YES;
        }
    }
}

@end